package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.heima.common.constants.user.UserConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ApAuthorFeign;
import com.heima.user.feign.WmUserFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import java.util.Date;
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    //按照状态查询用户认证列表
    @Override
    public ResponseResult  loadListByStatus(AuthDto dto) {
        if(ObjectUtils.isEmpty(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();//分页参数检查
        //根据状态分页查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        //分页条件构建
        IPage<ApUserRealname> pageParam=new Page<>(dto.getPage(),dto.getSize());
        IPage<ApUserRealname> page = page(pageParam, wrapper);
       //返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }
    //审核
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private ApAuthorFeign authorFeign;
    @Autowired
    private WmUserFeign wmUserFeign;
    @Transactional
//    @LcnTransaction
    //    @GlobalTransactional//开启分布式事务注解
    @Override
    public ResponseResult updateStatusById(AuthDto dto,Integer status) {
        //1.检查参数
        if(dto == null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.检查状态
        if(checkStatus(status)){//如果状态为空，或者不为2（审核失败）或9（审核成功）
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.1修改状态
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if(dto.getMsg()!=null) {//如果拒绝原因不为空
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //3.如果状态为审核通过,创建自媒体用户
        if(status.equals(UserConstants.PASS_AUTH)){
            ResponseResult result = createWmUserAndAuthor(dto);
                if(result!=null) {
                        return result;
                }
            }
        int i=10/0;
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    //创建自媒体用户
    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        //3.1查看自媒体是否存在
        Integer apUserRealnameId = dto.getId();
        ApUserRealname apUserRealname = getById(apUserRealnameId);
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
//        ApUser apUser = apUserMapper.selectById(getById(dto.getId()).getUserId());
        //根据认证id查询实名认证中的uesrid，再根据用户id得到app用户信息
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = wmUserFeign.findByname(apUser.getName());//远程调用查询自媒体账户
        if(wmUser==null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(UserConstants.PASS_AUTH);
            wmUserFeign.save(wmUser);
        }
            createAuthor(wmUser);//创建作者
            apUser.setFlag((short)1);//标记自媒体人
            apUserMapper.updateById(apUser);
            return null;
    }
    private void createAuthor(WmUser wmUser) {
        //创建作者信息
        ApAuthor apAuthor = authorFeign.findById(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setType(UserConstants.AUTH_TYPE);
            authorFeign.save(apAuthor);
        }
    }
    //检查状态
    private boolean checkStatus(Integer status) {
        if(status == null || (!status.equals(UserConstants.FAIL_AUTH) && !status.equals(UserConstants.PASS_AUTH))){
            return  true;
        }
        return false;
    }
}
